package web

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-iot-gateway/internal/logger"
	sys_config "go-iot-gateway/internal/sys/config"
	"net/http"
	"time"
)

var webServer *http.Server

func CloseWebApp(ctx context.Context) {
	if webServer != nil {
		err := webServer.Shutdown(ctx)
		logger.Web().Error("web 关闭失败", err)
	}
}

// 基于 web 页面的管理器
func StartWebApp() {
	webEnv := sys_config.ConfigInfo().WebEndpoint

	fmt.Printf("\n ===== 初始化WEB ===== \n")
	jsonData, _ := json.Marshal(webEnv)
	fmt.Printf("%s \n", string(jsonData))

	if !webEnv.Enable {
		return
	}

	if webEnv.RunMode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}

	r := gin.Default()      //创建一个路由
	configRouter(webEnv, r) //路由配置

	webServer = &http.Server{
		Addr:           webEnv.Address + ":" + webEnv.Port,
		Handler:        r,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := webServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Web().Error("Web Endpoint 启动失败 ", err)
			panic("web 服务启动失败")
		}
	}()

}
